package org.zhouyi.nativedemo.utils;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 根据id获取锁:争对同一个id上锁，不同id不影响
 *
 * @author ZhouYi
 */
public class LockUtil {
    static ConcurrentHashMap<Object, Object> map = new ConcurrentHashMap<>();

    public static Object getLock(Object id) {
        map.putIfAbsent(id, new Object());
        return map.get(id);
    }

    public static void unLock(Object id) {
        map.remove(id);
    }

    /*
    demo
    void demo(){
        Integer userId = 10000;
        synchronized (LockUtil.getLock(userId)){
            try{
                // TODO
            }finally {
                LockUtil.unLock(userId);
            }
        }
    }
    */
}
